/**
 * 
 */
package tr.edu.ozyegin.ccrg.wekaPerformanceRun;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Class to be created that implements JobThread interface and created via
 * Factory Method Class ParallalTest
 * 
 * @author im1076
 * @since 3.7.2011
 * @version 0.1
 * @see JobThread ParallelJobTest WekaParallelJobTest
 */
public class WekaJobThread extends JobThread {

	private boolean isDebug = false;

	private static int i = 0;
	
	/**
	 * Constructor
	 */
	public WekaJobThread() {
 	}

	/**
	 * Constructor
	 */
	public WekaJobThread(boolean _isDebug) {
		this.isDebug = _isDebug;
	}

	@Override
	public Runnable getRunnableJobTread() {
		// TODO Auto-generated method stub
		return this.runnableWeka;
	}

	@Override
	public void setRunnableJobTread(Runnable _runnableJobTread) {
		// TODO Auto-generated method stub
	}

	Runnable runnableWeka = new Runnable() {

		public void run() {

			runProcess();

			TestController.getSingletonedTestContoller()
					.incrementFinishedTestAmount();

		}

		private void runProcess() {
			// TODO Auto-generated method stub

			try {

				// TODO Zaman ayarları TestController classı ile haberleşerek
				// oluşturulacak

				processRunCommand = new WekaProcessRunCommand();

				Process p = processRunCommand.execute();

				
				
				
				Properties localWekaPerformanceProperties = TestController.getSingletonedTestContoller().getWekaPerformanceProperties();

				
				
				// check if it is debug mode
				if (localWekaPerformanceProperties.getProperty("debugMode").equalsIgnoreCase("true")){
 				
				
				String line;
				String consoleOutput = "";

				try {

					BufferedReader input = new BufferedReader(
							new InputStreamReader(p.getInputStream()));
					while ((line = input.readLine()) != null) {
						consoleOutput = consoleOutput + "\n" + line;

					}
					input.close();
				} catch (Exception err) {
					err.printStackTrace();
				}

				
					if (localWekaPerformanceProperties.getProperty("printConsole").equalsIgnoreCase("true")){
						//Process console çıktısı çok uzun olduğundan dolayı ekrana basılması her zaman istenen bir durum değil kapatılıyor.
						
						System.out.println(consoleOutput);
					}

				
				
				String wekaTestDirectory = localWekaPerformanceProperties.getProperty("wekaTestDirectory");
				
				// Create a directory; all non-existent ancestor directories are
				// automatically created
				boolean success = (new File(wekaTestDirectory)).mkdirs();
				if (!success) {
					// Directory creation failed
				}

				try {
					BufferedWriter out = new BufferedWriter(
							new FileWriter(
									wekaTestDirectory + "testResult"+ ++i +".txt"));
					out.write(consoleOutput);
					out.close();
				} catch (IOException e) {
				}
				
				
				String s ="";
				
				
				Process pDiff = Runtime.getRuntime().exec("diff "+wekaTestDirectory+"testResult1.txt "+wekaTestDirectory+"testResult"+ i+".txt");                                                                                                                                                     
				BufferedReader stdInput = new BufferedReader(new InputStreamReader(pDiff.getInputStream()));
				while ((s = stdInput.readLine()) != null) {
				        System.out.println(s);
				}
				  
				
				
				if (localWekaPerformanceProperties.getProperty("deleteWekaTestDirectory").equalsIgnoreCase("true")){
					deleteDir(new File(wekaTestDirectory));
				}

				

				
				
				
				
				} // end of properties file check debug mode
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("---- exception at Process p = Runtime ");

				e.printStackTrace();

			}

		}

	};
	
	
	// Deletes all files and subdirectories under dir.
	// Returns true if all deletions were successful.
	// If a deletion fails, the method stops attempting to delete and returns false.
	public static boolean deleteDir(File dir) {
	    if (dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i=0; i<children.length; i++) {
	            boolean success = deleteDir(new File(dir, children[i]));
	            if (!success) {
	                return false;
	            }
	        }
	    }

	    // The directory is now empty so delete it
	    return dir.delete();
	}

}// end of class
